<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model.trim="query.query.materialName" clearable placeholder="请输入货品名称" @keyup.enter.native="search" />
      <el-date-picker v-model="q_p_formDate1" format="yyyy-MM-dd" value-format="yyyy-MM-dd" type="daterange"
        range-separator="-" start-placeholder="起始日期" end-placeholder="终止日期" @change="q_p_selectTimecreate" />
      <el-button type="primary" icon="el-icon-search" @click="search">
        {{ $t('table.search') }}
      </el-button>
      <el-button @click="handleExport" type="primary" icon="el-icon-download">
        {{ $t("table.export") }}
      </el-button>
    </div>
    <el-table :data="tableData" row-key="id" highlight-current-row border
      :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
      <el-table-column prop="materialNo" label="货品编码" />
      <el-table-column label="货品名称" prop="materialName" />
      <el-table-column label="单位" prop="unit" />
      <el-table-column prop="model" label="规格" align="center" />
      <el-table-column prop="startStoreNum" label="上期结存（数量）" align="center" width="140" />
      <el-table-column prop="startStoreAmount" label="上期结存（金额）" align="center" width="140" />
      <el-table-column prop="currentInStoreNum" label="本期收入（数量）" align="center" width="140" />
      <el-table-column prop="currentInStoreAmount" label="本期收入（金额）" align="center" width="140" />
      <el-table-column prop="currentOutStoreNum" label="本期发出（数量）" align="center" width="140" />
      <el-table-column prop="currentOutStoreAmount" label="本期发出（金额）" align="center" width="140" />
      <el-table-column prop="endStoreNum" label="本期结存（数量）" align="center" width="140" />
      <el-table-column prop="endStoreAmount" label="本期结存（金额）" align="center" width="140" />
      <el-table-column :label="$t('table.actions')" align="center" fixed="right">
        <template slot-scope="{ row, $index }">
          <el-button type="primary" size="mini" @click="handleUpdate(row.materialId)">
            明细
          </el-button>
          <!-- <el-button type="primary" size="mini" @click="handleDetailExport(row)">
            明细导出
          </el-button> -->
        </template>
      </el-table-column>
    </el-table>
    <el-pagination style="margin-top: 20px;" :current-page="query.pageIndex" :page-sizes="[5, 10, 20, 50]"
      :page-size="query.pageSize" layout="total, sizes, prev, pager, next, jumper" :total="total"
      @size-change="handleSizeChange" @current-change="handleCurrentChange" />
    <el-dialog title="明细" :visible.sync="dialogVisible" width="80%" :close-on-click-modal="false">
      <el-date-picker style="margin-right: 10px;" v-model="q_p_formDate1_detail" format="yyyy-MM-dd"
        value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="起始日期" end-placeholder="终止日期"
        @change="q_p_selectTimecreate_detail" />
      <el-select style="margin-right: 10px;width: 220px;" v-model="detailQuery.warehouseId" placeholder="请选择仓库"
        clearable>
        <el-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.id" />
      </el-select>
      <el-checkbox style="margin-right: 10px;" v-model="check" @change="handleCheck">是否调拨</el-checkbox>
      <el-button type="primary" icon="el-icon-search" @click="handleUpdate()">
        {{ $t('table.search') }}
      </el-button>
      <el-button @click="handleDetailExport" type="primary" icon="el-icon-download">
        {{ $t("table.export") }}
      </el-button>
      <el-table style="margin-top: 20px;" :data="gridData" highlight-current-row border
        :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
        <el-table-column prop="bizType" label="业务类型" />
        <el-table-column label="开单日期" prop="changeTime" width="160px">
          <template slot-scope="{ row }">
            <span>{{ row.changeTime | parseTime('{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="billNo" label="单据号" width="160px" />
        <el-table-column prop="partnerName" label="参与方名称" width="160px" />
        <el-table-column prop="unit" label="单位" />
        <el-table-column prop="inStoreNum" label="本期收入（数量）" width="140px" />
        <el-table-column prop="inStoreCost" label="本期收入（成本价）" width="150px" />
        <el-table-column prop="inStoreAmount" label="本期收入（金额）" width="140px" />
        <el-table-column prop="outStoreNum" label="本期发出（数量）" width="140px" />
        <el-table-column prop="outStoreCost" label="本期发出（成本价）" width="150px" />
        <el-table-column prop="outStoreAmount" label="本期发出（金额）" width="140px" />
        <el-table-column prop="inventoryNum" label="期末结存（数量）" width="140px" />
        <el-table-column prop="inventoryCost" label="期末结存（成本价）" width="150px" />
        <el-table-column prop="inventoryAmount" label="期末结存（金额）" width="140px" />
      </el-table>
    </el-dialog>
  </div>
</template>
<script>

import waves from '@/directive/waves' // waves directive
import { wmsStockPageAccountList, wmsStockExportStoreAccountExcel, wmsStockChangeDetailList, wmsStockChangeExportExcel } from '@/api/qmsQualityManagement'
import { warehousePageList } from '@/api/qmsQualityManagement'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { downfile } from "@/utils";

export default {
  name: 'Project',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      gridData: [],
      dialogVisible: false,
      q_p_formDate1: [],
      query: {
        pageIndex: 1,
        pageSize: 10,
        query: {}
      },
      total: 0,
      tableData: [],
      q_p_formDate1_detail: [],
      detailQuery: {},
      warehouseList: [],
      check:true,
      detailQuery: {
        isShowTransfer: '1'
      }
    }
  },
  mounted() {
    this.getday()
    this.getInfo()
    this.getWarehousePageList()
  },
  methods: {
    handleCheck(e){
      this.detailQuery.isShowTransfer = e ? '1' : '0'
    },
    getWarehousePageList() {
      warehousePageList({
        query: { state: "1" }
      }).then(res => {
        this.warehouseList = res
      })
    },
    async handleUpdate(id) {
      if (id){
        this.detailQuery.materialId = id
        this.getDetailDay()
      }
      this.gridData = await wmsStockChangeDetailList(this.detailQuery)
      this.dialogVisible = true
    },
    q_p_selectTimecreate_detail(val) {
      if (val) {
        this.detailQuery.startDate = val[0]
        this.detailQuery.endDate = val[1]
      } else {
        this.detailQuery.startDate = this.detailQuery.endDate = ''
      }
    },
    getDetailDay() {
      const currDate = new Date().toLocaleDateString()// 2020/11/6
      const arrs = currDate.split('/')
      const arrs1 = arrs.join('-')
      const yy = parseInt(arrs[0]);
      const mm = parseInt(arrs[1]);
      const dd = parseInt(arrs[2]);
      const pdStr = new Date(yy, mm - 1, 1).toLocaleDateString().split('/').join('-');
      this.detailQuery.startDate = pdStr
      this.detailQuery.endDate = arrs1
      this.q_p_formDate1_detail = [pdStr, arrs1]
    },
    async handleDetailExport(row) {
      try {
        await wmsStockChangeExportExcel(this.detailQuery)
      } catch (err) {
        const reader = new FileReader();
        reader.readAsText(err);
        reader.onload = (event) => {
          const resultString = reader.result; // 这里就是转换后的字符串
          if (resultString.includes('code') && resultString.includes('isSuccess')) {
            this.$message.error(JSON.parse(resultString).message)
          } else {
            downfile('仓库帐面库存明细.xlsx', err);
          }
        }
      }
    },
    async handleExport() {
      try {
        const { query } = this.query
        await wmsStockExportStoreAccountExcel(
          query
        )
      } catch (err) {
        const reader = new FileReader();
        reader.readAsText(err);
        reader.onload = (event) => {
          const resultString = reader.result; // 这里就是转换后的字符串
          if (resultString.includes('code') && resultString.includes('isSuccess')) {
            this.$message.error(JSON.parse(resultString).message)
          } else {
            downfile('仓库帐面库存汇总.xlsx', err);
          }
        }
      }
    },
    getday() {
      const currDate = new Date().toLocaleDateString()// 2020/11/6
      const arrs = currDate.split('/')
      const arrs1 = arrs.join('-')
      this.query.query.beginDate = this.query.query.endDate = arrs1
      this.q_p_formDate1 = [arrs1, arrs1]
    },
    q_p_selectTimecreate(val) {
      const { query } = this.query
      if (val) {
        query.beginDate = val[0]
        query.endDate = val[1]
      } else {
        this.$nextTick(() => {
          this.getday()
        })
      }
    },
    handleCurrentChange(currentPage) {
      this.query.pageIndex = currentPage
      this.getInfo()
    },
    handleSizeChange(size) {
      this.query.pageSize = size
      this.getInfo()
    },
    search() {
      this.query.pageIndex = 1
      this.getInfo()
    },
    getInfo() {
      wmsStockPageAccountList(this.query).then((res) => {
        const { records, total } = res
        this.tableData = records
        this.total = total
      })
    },
  }
}
</script>

<style scoped>
.addinput /deep/ .el-input__inner {
  border: none;
  background: #f5f7fa;

}

.addinput /deep/ .el-textarea__inner {
  border: none;
  background: #f5f7fa;

}

.downfile {
  text-decoration: underline;
  color: blue;
}
</style>
